"""
Python module to interact indian railways website.
"""

import urllib
from elementtidy import TidyHTMLTreeBuilder
import pprint

def ticket_status(pnr):
    """Return reservation status of the ticket specified by the 10 digit PNR number."""
    pass

def reservation_enquiry(train, frm, to, when):
    """Check the current status of reservation for the desired journey in the desired train."""
    pass

def all(seq):
    for a in seq:
        if a is False:
            return False
    return True

def parse_table(root, attrs):
    def match(t):
        return all(t.attrib.get(k) == v for k, v in attrs.items())

    tables = filter(match, root.findall('.//{http://www.w3.org/1999/xhtml}table'))
    if tables:
        rows = tables[0].findall('.//{http://www.w3.org/1999/xhtml}tr')
        return [[td.text for td in tr.getchildren()] for tr in rows]
    return None
    
def running_status(train, date):
    """Return the running status of a train.
        >>> running_status("434SC", "30/05/2007")
    """
    url = 'http://www.trainenquiry.com/RunningTT_Display.aspx'
    data = urllib.urlencode(dict(drop_sel=train, date=date))
    result = urllib.urlopen(url + '?' + data)
    html = TidyHTMLTreeBuilder.parse(result).getroot()
    return parse_table(html, {'class' : 'Table_rows'})

def train_schedule(train, date):
    """Returns the schedule of the train. 
    XXX: What is the need of date here?
    """
    url = 'http://www.trainenquiry.com/Schedule_Display.aspx'
    data = urllib.urlencode(dict(drop_sel=train, date=date))
    print url, data
    result = urllib.urlopen(url + '?' + data)
    html = TidyHTMLTreeBuilder.parse(result).getroot()
    return parse_table(html, {'class' : 'Table_rows'})

